import { addMoment, listMoment } from '@/services/api';
import { formatDate } from '@/utils';
import { LikeOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';
import { ProList } from '@ant-design/pro-components';
import { Button, Divider, Input, message, Skeleton, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import {useNavigate} from "@umijs/max";

const IconText = ({ icon, text }: { icon: any; text: string }) => (
  <span>
    {React.createElement(icon, { style: { marginInlineEnd: 8 } })}
    {text}
  </span>
)

const MomentList = () => {
  const [dataSource, setDataSource] = useState([]);
  const [moment, setMoment] = useState('');
  const [hasMore, setHasMore] = useState(true); // 用于判断是否有更多数据
  const [page, setPage] = useState(1); // 当前页数

  const navigate = useNavigate()
  // 获取动态列表
  const fetchMomentList = async (reset=false) => {
    try {
      const currentPage = reset ? 1: page;
      const res = await listMoment({current: currentPage, pageSize: 10 });
      const records = res.data.records;
      if (reset) {
        setDataSource(records)
        setHasMore(records.length < res.data.total);  // 判断是否还有更多数据
        setPage(2)
      } else {
        setDataSource(prev => [...prev, ...records]) // 更新数据源
        setHasMore(dataSource.length + records.length < res.data.total);
        setPage((prev) => prev + 1); // 递增页数
      }
    } catch (error: any) {
      message.error('获取动态列表失败');
    }
  };

  // 发布动态
  const handlePublish = async () => {
    if (!moment || moment.trim() === '') {
      setMoment('');
      return message.warning('请输入要发布的动态~');
    }
    if (moment.length > 500) {
      // 假设限制为500个字符
      return message.warning('动态内容不能超过500个字符~');
    }
    try {
      await addMoment({ content: moment });
      message.success('发布成功~');
      await setMoment(''); // 清空输入框
      fetchMomentList(true); // 重新获取动态列表
    } catch (error: any) {
      message.error(error.message);
    }
  };

  useEffect(() => {
    fetchMomentList();
  }, []);

  // 跳转到对应文章的页面
  function handleItemClick(record: Record<string, any>) {
    navigate(`/moment-detail/${record.id}`);
  }

  return (
    <div id="scrollableDiv" style={{ height: '80vh', overflow: 'auto' }}>
      <Input.TextArea
        rows={6}
        placeholder="一起分享你的趣事吧~"
        value={moment}
        onChange={(e) => setMoment(e.target.value)}
      />
      <InfiniteScroll
        dataLength={dataSource?.length}
        next={() => fetchMomentList()}
        hasMore={hasMore}
        loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
        endMessage={<Divider plain>我是有底线的~ 🤐</Divider>}
        scrollableTarget="scrollableDiv"
      >
        <ProList
          // 工具栏渲染
          toolBarRender={() => {
            return [
              <Button key="3" type="primary" onClick={handlePublish}>
                发布
              </Button>
            ]
          }}
          itemLayout="vertical" // 垂直布局
          rowKey="id"
          dataSource={dataSource}
          metas={{ // 目标渲染
            title: { // 用户名
              render: (_, record) => (
                <div onClick={e => handleItemClick(record)}>
                  <a style={{ fontSize: 18, fontWeight: 700 }}>
                    {record.user_name}
                  </a>
                  <span style={{ marginLeft: 8, fontSize: 12 }}>
                    发布于 {formatDate(record.createAt)}
                  </span>
                </div>
              ),
            },
            description: { // 标签
              render: () => (
                <>
                  <Tag>语雀专栏</Tag>
                  <Tag>设计语言</Tag>
                  <Tag>蚂蚁金服</Tag>
                </>
              ),
            },
            actions: { // 点赞/收藏/评论 数量
              render: (_, record) => [
                <IconText icon={StarOutlined} text="666" key="list-vertical-star-o" />,
                <IconText icon={LikeOutlined} text="666" key="list-vertical-like-o" />,
                <IconText
                  icon={MessageOutlined}
                  text={record.commentCount}
                  key="list-vertical-message"
                />,
              ],
            },
            extra: { // 图片显示
              render: (_, record: any) => (
                <img
                  width={100}
                  height={100}
                  alt="logo"
                  src={
                    record.user_avatar ||
                    'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'
                  }
                />
              ),
            },
            content: { // 内容
              render: (_, record) => (
                <div style={{ marginLeft: -30 }}>
                  {record.content}
                </div>
              )
            },
          }}
        />
      </InfiniteScroll>
    </div>
  );
};

export default MomentList;
